/**
 * Copyright 2016 Qiyi Inc. All rights reserved.
 *
 * @file:   StatisticSty2.Base.js
 * @path:   js-src/StatisticSty2/
 * @desc:   StatisticSty2模块下基础业对象类
 * @author: zhang@qiyi.com
 * @date:   2016-03-28
 */
qui(
	function(require, exports, module){

        StatisticSty2.Grid = function(options) {
            this.dao = StatisticSty2.Dao;
            this.config = StatisticSty2.Config;
            this.options = options || {};
            this.exportExcel = false;
        };

        Com.inherits(StatisticSty2.Grid, Ancestor.Grid).extend({
            init: function() {
                var self = this;
                var $container = self.options.$container;
                self.$hiddenGrid = self.options.$hiddenGrid;
                self.$grid = $container.find('table.grid');
                self.queryStringObj = StatisticSty2.queryStringObj();
                self.bindEvent();
                self.initSuggest();
            },


			run : function()
			{

                this.start();

			},
		
            start: function(options, callback) {
                var self = this;
				self.init();
				
                var gridConfig = self.getGridConfig();
					//self.echoQuery();
				
                options = $.extend(true, {
                      width: 1500,
                  //  shrinkToFit: false,
                    //autowidth: true
                }, gridConfig, options);
                self.initGrid.call(this, options, callback);

				$('body').on('click','a.disabled',function(e){
				  e.preventDefault();
				});

            },

            initGrid: function(options, callback) {
				var self = this;
				var params = self.getParam();			

                var gridConfig = self.getGridConfig();
                var $gridContainer = self.options.$container;
                var $pager = $gridContainer.find('div.pager');
                var $grid = $gridContainer.find('table.grid');

				//params.rowNum=10;
				
                options = $.extend(true, {
                    pager: $pager,
                    mtype: 'post',
					
                   postData: $.extend(true, {}, params),
				   
                }, gridConfig, options);
				
             //   $grid.jqGrid('scroll', {});
				
				//console.log(options	);
				
                $grid.jqGrid(options);

            },
            initSuggest:function(){

                var emailSuggest = {
                    options: {
                        source: "/api/redirect",
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            var requestData = {url: "http://lego.iqiyi.com/external/auth/auth-api/services/user/search", type: "get", params: {email: term}, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item["userName"];
                                itemData[options.labelKey] = item["email"];
                                itemData["value"] = item["userName"];
                                itemData["email"] = item["email"];
                                itemData["uid"] = item["uid"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.id + "(" + item.label + ")";
                        }
                    }
                }
                $("input[name=user]").suggest(emailSuggest.options);

                var programNameSuggest = {
                    options: {
                        source: "/api/suggest/statisticSty2",
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        getParam: function (term) {
                            return {"field": "programName", timeSign: new Date().getTime()}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = json.data == null ? null : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            $.map(data, function (item) {
                                itemData = {};
                                itemData[options.valueKey] = item;
                                itemData[options.labelKey] = item;
                                itemData["value"]= item;
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return item.label;
                        }
                    }
                }
                $("input[name=programName]").suggest(programNameSuggest.options);
            },
			jsonConvert : function (jsonstr,o){
                    if (jsonstr && typeof jsonstr === 'string') {
						var _jsonparse = false;
						if($.jgrid.useJSON) {
							$.jgrid.useJSON = false;
							_jsonparse = true;
						}
                        var json = $.jgrid.parse(jsonstr);
						if(_jsonparse) { $.jgrid.useJSON = true; }
                        var gprm = json[o.jsonGrid.config];
                        var jdata = json[o.jsonGrid.data];
                        if(jdata) {
                            var svdatatype = gprm.datatype;
                            gprm.datatype = 'jsonstring';
                            gprm.datastr = jdata;
                            $($t).jqGrid( gprm ).jqGrid("setGridParam",{datatype:svdatatype});
                        } else {
                            $($t).jqGrid( gprm );
                        }
                    }
                },
            query: function() {
                var self = this;
                var $container = self.options.$container;
                var $grid = self.$grid;
                self.overridePostData($grid);
                var params = self.getParam();
	
                $grid.jqGrid('setGridParam', {
                    postData: params,
                }).trigger('reloadGrid', [{
                    page: 1
                }]);
            },


            getParam: function() {
                var self = this;
                var $container = self.options.$container;

                var $grid = self.$grid;
                var params = {};
                var $form = $container.find('form[name="basicFrm"]');

                var $elements = $.makeArray($form.prop('elements')).filter(function() {
                    return true; //this.name; 
                });

                var name;
                var key;
                $.each($elements, function() {
                    name = this.name;
                    if (name) {

                            if(this.type=='radio')
							{	
								params[name] = $('input[name="'+name+'"]:checked').val() || '';
							}
							else
                            params[name] = $.trim($(this).val()) || '';
                    }

                });

                var queryStringObj = self.queryStringObj;
                if (queryStringObj['channelId']) {
                    $.extend(params, {channelId : queryStringObj['channelId']});
                }
                if (queryStringObj['albumName']) {
                    $.extend(params, {albumName : decodeURIComponent(queryStringObj['albumName'])});
                }
                if (queryStringObj['categoryName']) {
                    $.extend(params, {categoryName : decodeURIComponent(queryStringObj['categoryName'])});
                }
                return params;
            },

            bindEvent: function() {
                var self = this;
                self.bindBasicEvent();
            },



            bindBasicEvent: function() {
                var self = this;
                var $container = self.options.$container;
                var $form = $container.find('form[name="basicFrm"]');
                self.bindFormEvent($form);
                self.bindFormData($form);

                $container.find('.query-btn').on('click.query', function() {
				    self.query();
                    return false;
                });

                $("div.query").keydown(function(event){
                    if(event.keyCode == 13)
                    {
                            self.query();
                            return false;
                    }
                });

                $form.find('button[name="reset"]').click(function() {
                    var $elements = $.makeArray($form.prop('elements')).filter(function() {
                        return true; //this.name;
                    });
                    var name;
                    $.each($elements, function() {
                        name = this.name;
                        if (name) {
                                $.trim($(this).val(""));
                        }
                    });
                    self.bindFormData($form);
                });

                $container.find("button.query-excel").bind("click", function (event) {
                    self.$hiddenGrid.html("");
                    $("button.query-excel").prop("disabled", "disabled")
                    self.doExportExcel();
                })

            },
            doExportExcel: function () {
                var self = this;
                var params = self.getParam();
                params.pageSize = 5000;
                self.dao.getExportDataAll(params,{
                    lockHandler:function(){
                        $("button.query-excel").prop("disabled", "disabled")
                    },
                    flushCheck:function(curNum){
                        return curNum >= 5000
                    },
                    phaseHandler:function (dataArr,fileName) {
                        self.doExportExcelAllCallBack(dataArr,"长视频智能分析");
                    },
                    unlockHandler:function(){
                        $("button.query-excel").removeAttr("disabled")
                    }
                });
            },
            doExportExcelAllCallBack: function (dataArr, fileName) {
                var self = this
                if (dataArr != null && dataArr.length > 0) {
                    self.$hiddenGrid.append(StatisticSty2.Util.buildTH(self.config.TABLE_HIDDEN.colNames))
                    $.each(dataArr, function (i, element) {
                        self.$hiddenGrid.append(StatisticSty2.Util.buildTD(element, self.config.TABLE_HIDDEN.colModel))
                    })
                }
                if (fileName != null) {
                    self.$hiddenGrid.tableToExcel({name: fileName});
                } else {
                    self.$hiddenGrid.tableToExcel();
                }
                self.$hiddenGrid.html("");
            },
            doExportExcelCallBack: function (data) {
                var self = this
                if (data != null && data.data.result.length > 0) {
                    self.$hiddenGrid.append(StatisticSty2.Util.buildTH(self.config.TABLE_HIDDEN.colNames))
                    $.each(data.data.result, function (i, element) {
                        self.$hiddenGrid.append(StatisticSty2.Util.buildTD(element, self.config.TABLE_HIDDEN.colModel))
                    })
                }
                self.$hiddenGrid.tableToExcel();
                self.$hiddenGrid.html("");
                console.log("excel build end");
                $("button.query-excel").removeAttr("disabled")
            },

            bindFormEvent: function($form) {
                var self = this;
                $form.find('input[name="startDate"]').datetimepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="endDate"]').datepicker("option", "minDate", selectedDate);
                    },
                    yearRange: '2010:+0'
                });

                $form.find('input[name="endDate"]').datetimepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="startDate"]').datepicker("option", "maxDate", selectedDate);
                    },
                    yearRange: '2010:+0'
                });

                $form.find('input[name="categoryName"]').keydown(function(event){

                });

				fillFieldNameWhenChangeSelect($form, 'query-select-control', 'query-input-text');
			},

            bindFormData: function($form) {
                var currentDate = new Date();
                currentDate.setHours(0);
                currentDate.setSeconds(0);
                currentDate.setMinutes(0);
                currentDate.setTime(currentDate.getTime() + 86400000 );
                var searchEnd = currentDate.format("yyyy-MM-dd hh:mm:ss");
                currentDate.setTime(currentDate.getTime() - 7*86400000 );
                var searchBegin = currentDate.format("yyyy-MM-dd hh:mm:ss");
                $("input[name=endDate]").datetimepicker("option", "minDate", searchBegin);
                $("input[name=endDate]").datetimepicker("option", "minDateTime", new Date(searchBegin.replace(/-/g, "/")));
                $("input[name=startDate]").datetimepicker("option", "maxDate", searchEnd);
                $("input[name=startDate]").datetimepicker("option", "maxDateTime", new Date(searchEnd.replace(/-/g, "/")));
                $("input[name=endDate]").datetimepicker("setDate",new Date(searchEnd.replace(/-/g, "/")));
                $("input[name=startDate]").datetimepicker("setDate",new Date(searchBegin.replace(/-/g, "/")));
            },
        });

	}
);
